public class HashBuck {
    static class Node{
        public int key;
        public int value;
        public Node next;
        public Node(int key,int value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node[] array = new Node[10];
    public int usidSize;
    public static final double LOAD_FACTOR = 0.75;//负载因子
    public void push(int key,int value) {
        Node node = new Node(key,value);
        //1.找到位置
        int index = key % array.length;
        //2.遍历数组，是否有相同的元素，更新value
        //如果是空数组，直接采用插入
        Node cur = array[index];
       /* if(cur == null) {
            array[index] = node;
            usidSize++;
            return;
        }
*/
        while(cur != null) {
            //找到相同元素，修改value值
            if (cur.key == key) {
                cur.value = value;
                usidSize++;
                return;
            }
            cur = cur.next;
        }
        //没有找到cur.key == key
        //头插
        node.next = array[index];
        array[index] = node;
        usidSize++;
        //负载因子超过0.75
        if(loadFactor() >= 0.75) {
            //数组扩容后重新哈希
            reSize();
        }
    }
    //扩容，重新哈希
    private void reSize() {
        Node[] newArray = new Node[array.length*2];
        //处理重新哈希
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                //拿到映射的新下标
                int index = cur.key%newArray.length;
                //记录之前cur.next
                Node curNext = cur.next;
                //插入到新下标,头插法。
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        //把数组给到原数组
        array = newArray;
    }

    //负载因子的计算
    private double loadFactor() {
        return usidSize*1.0 / array.length;
    }
    public void get(int key) {
        //找到位置
        int index = key % array.length;
        //遍历数组
        Node cur = array[index];
        while (cur != null) {
            if(cur.key == key) {
                System.out.println(cur.value);
            }
            cur = cur.next;
        }
    }
}
